package utils;

import book.Book;
import com.bit.utils.FileUtils;

import java.time.LocalDate;

public class AnalyzingBook {
    /**
     *
     * @param books 代表书籍数组对象
     * @param fileName 代表⽂件名称【如果不存在该⽂件，会⾃动创建该⽂件】
     */
    //给文件写数据
    public void storeObject(Book[] books, String fileName) {
        //计算有效书籍数
        int booksUseLen = 0;
        for (int i = 0; i < books.length; i++) {
            if(books[i] != null) {
                booksUseLen++;
            } else {
                break;//读取到空的数据直接退出了,因为后面用用效数遍历时也是用了 for 循环
            }
        }
        // StringBuilder 拼接时性能相对较高
        StringBuilder jsonArray = new StringBuilder();
        for (int i = 0; i < booksUseLen; i++) {
            if(books[i] != null) {
                jsonArray.append(books[i].toJSON());
                if(i != booksUseLen-1) {
                    //⼀本书籍完成后以\n进⾏分割
                    jsonArray.append("\n");
                }
            }
        }
        //数据写⼊⽂件
        FileUtils.writeFile(jsonArray.toString(),fileName);

    }

    //从文件读数据
    public Book[] loadObject(String fileName) {
        //从文件读取数据
        String content = FileUtils.readFile(fileName);
        if(content == null || content.isEmpty()) {
            System.out.println("File is empty or does not exist: " + fileName);
            return null;
        }
        //使用\n作为分割符进行字符串分割
        String[] booksJsonStrings = content.split("\n");

        Book[] books = new Book[booksJsonStrings.length];

        for (int i = 0; i < booksJsonStrings.length; i++) {
            books[i] = parseBookJson(booksJsonStrings[i]);
        }

        return books;
    }

    //把读出来的数据进行解析
    private Book parseBookJson(String json) {
        if(json.isEmpty()) {
            return null;
        }

        String[] pairs = json.split(",");

        int bookId = Integer.parseInt(pairs[0]);
        String title = pairs[1];
        String author = pairs[2];
        String category = pairs[3];
        int publishYear = Integer.parseInt(pairs[4]);
        boolean isBorrowed = Boolean.parseBoolean(pairs[5]);
        int borrowCount = Integer.parseInt(pairs[6]);
        LocalDate shelfDate = LocalDate.parse(pairs[7]);

        //构造书籍对象
        if (title != null && author != null && category != null && shelfDate != null) {
            Book book = new Book(title,author,category,publishYear,shelfDate);
            book.setBookId(bookId);
            book.setBorrowCount(borrowCount);
            book.setBorrowedStatus(isBorrowed);
            return book;
        }
        return null;
    }

}
